package com.itheima.exception;

import com.itheima.pojo.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e){
        return Result.error("出错啦，请联系管理员~");
    }

    @ExceptionHandler
    public Result handleClazzNotEmptyException(ClazzNotEmptyException e){
        return Result.error("该班级下还有学生，不能删除！");
    }

    @ExceptionHandler
    public Result handleDeptNotEmptyException(DeptNotEmptyException e){
        return Result.error("该部门下还有员工，不能删除！");
    }
    @ExceptionHandler
    //DuplicateKeyException 是数据库主键冲突异常
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errorMessage = message.substring(i);
        String[] arr = errorMessage.split(" ");

        return Result.error(arr[2] + " 已存在");
    }

}
